<template>
  <a-form class="living-form" :model="formData" layout="vertical">
    <template v-for="(module, index) in formData" :key="index">
      <a-form-item class="itemTitle">
        <div class="title">{{ module.name }}</div>
      </a-form-item>
      <a-row :gutter="[16, 16]">
        <template v-for="(subitem, i) in module.list" :key="i">
          <template v-if="subitem.type.includes('单选')">
            <a-col class="gutter-row" :span="8" v-if="subitem.show">
              <a-form-item class="subitemName">
                <template #label>
                  {{ subitem.name }}
                  <span v-if="subitem.remark">({{ subitem.remark }})</span>
                </template>
                <a-select
                  :options="subitem.options"
                  v-model:value="subitem.value"
                  :disabled="subitem.options[0].disabled || disabled"
                  @change="changeOptions($event, subitem, index, module)"
                />
              </a-form-item>
            </a-col>
          </template>
          <template v-else-if="subitem.type.includes('多选')">
            <a-col class="gutter-row" :span="8" v-if="subitem.show">
              <a-form-item class="subitemName">
                <template #label>
                  {{ subitem.name }}
                  <span>({{ subitem.type }})</span>
                </template>
                <a-select
                  mode="multiple"
                  :options="subitem.options"
                  v-model:value="subitem.value"
                  :disabled="disabled"
                  @change="multipleSelectChange($event, subitem)"
                />
              </a-form-item>
            </a-col>
          </template>
          <template v-else>
            <a-form-item class="subitemNameCheckbox" v-if="subitem.show">
              <a-textarea
                style="width: 50%; padding: 9px 16px"
                v-model:value="subitem.inputText"
                :disabled="disabled"
                placeholder="请输入你的回答"
                :maxlength="500"
                :rows="2"
              />
            </a-form-item>
          </template>
        </template>
      </a-row>
    </template>
  </a-form>
</template>

<script setup lang="ts">
const changeOptions = (e: any, subitem: any, index: any, module: any) => {
  // if (subitem.questionCode === 'Q74' || subitem.questionCode === 'Q78') {
  //   if (e === '从不') {
  //     module.list.forEach((item: any) => {
  //       if (
  //         item.questionCode === 'Q74' ||
  //         item.questionCode === 'Q78' ||
  //         item.questionCode === 'Q77'
  //       ) {
  //         item.options.forEach((vo) => {
  //           vo.disabled = false
  //         })
  //       } else {
  //         item.options.forEach((vo) => {
  //           vo.disabled = true
  //         })
  //         item.value = undefined
  //       }
  //     })
  //   } else {
  //     module.list.forEach((item: any) => {
  //       item.options.forEach((vo) => {
  //         vo.disabled = false
  //       })
  //     })
  //   }
  // }

  subitem.options.map((vo: any) => {
    vo.check = false
    if (vo.value === e) {
      vo.check = true
      subitem.sort = vo.sort
    }
  })

  formData.value = showCondition(formData.value)
  // console.log(formData.value)
}
const multipleSelectChange = (e, data) => {
  if (e.includes('以上均无')) {
    data.value = ['以上均无']
    data.options.map((vo) => {
      vo.check = false
      if (vo.value === '以上均无') {
        vo.check = true
      }
    })
  }
}
const multipleChange = (e, val, item) => {
  console.log(e.target.check)
  if (e.target.check) {
    if (item.value.includes(val)) {
      return
    } else {
      item.value.push(val)
    }
  } else {
    const i = item.value.findIndex((v) => {
      return v === val
    })
    if (i > -1) {
      item.value.splice(i, 1)
    } else {
      return
    }
  }
}

const showCondition = (arr) => {
  const obj = {}
  arr.map((v) => {
    v.list.map((u) => {
      obj[u.id] = u
    })
  })

  const List = []

  for (const v of arr) {
    const L = v.list.filter((u) => {
      if (!u.showCondition) {
        return true
      }
      let show = true
      if (Object.prototype.hasOwnProperty.call(u.showCondition, 'show')) {
        show = u.showCondition.show
      }
      let r
      try {
        r = loop(u.showCondition, obj)
      } catch (e) {
        throw new Error(`自定义条件执行异常，异常问题：${u.name}`)
      }

      console.log(r)
      u.show = r
      // if (show) {
      //   return r
      // } else {
      //   return !r
      // }
      return true
    })
    if (L.length) {
      List.push({
        ...v,
        list: L
      })
    }
  }

  console.log(List)
  return List
}

const loop = (obj, d) => {
  if (obj.operator === 'AND') {
    return obj.conditions.every((v) => {
      if (v.operator !== 'AND' && v.operator !== 'OR') {
        if (v.operator === '填写完成') {
          return d[v.id].value.trim() !== ''
        } else {
          if (v.id === 'custom') {
            return transformCustom(v.value, d)
          } else if (d[v.id].type.includes('单选')) {
            return d[v.id].sort == v.value
          } else if (d[v.id].type.includes('多选')) {
            return d[v.id].sort.includes(v.value)
          } else if (d[v.id].type === '数字选择') {
            const f = transform(v)
            return f(d[v.id].value)
          } else if (d[v.id].type === '输入') {
            const f = transform(v)
            return f(d[v.id].value)
          }
          if (typeOf(d[v.id].value) === 'string') {
            return d[v.id].value.trim() !== ''
          } else if (typeOf(d[v.id].value) === 'array') {
            return d[v.id].value.length > 0
          } else {
            return true
          }
          // return f(d[v.id].value)
        }
      } else {
        return loop(v, d)
      }
    })
  } else if (obj.operator === 'OR') {
    return obj.conditions.some((v) => {
      if (v.operator !== 'AND' && v.operator !== 'OR') {
        if (v.operator === '填写完成') {
          return d[v.id].value.trim() !== ''
        } else {
          if (v.id === 'custom') {
            return transformCustom(v.value, d)
          } else if (d[v.id].type.includes('单选')) {
            return d[v.id].sort == v.value
          } else if (d[v.id].type.includes('多选')) {
            return d[v.id].sort.includes(v.value)
          } else if (d[v.id].type === '数字选择') {
            const f = transform(v)
            return f(d[v.id].value)
          } else if (d[v.id].type === '输入') {
            const f = transform(v)
            return f(d[v.id].value)
          }
          if (typeOf(d[v.id].value) === 'string') {
            return d[v.id].value.trim() !== ''
          } else if (typeOf(d[v.id].value) === 'array') {
            return d[v.id].value.length > 0
          } else {
            return true
          }
          // return f(d[v.id].value)
        }
      } else {
        return loop(v, d)
      }
    })
  }
  return true
}

const transform = (obj) => {
  if (typeOf(obj.value) === 'string') {
    return new Function('x', 'return x ' + obj.operator + ' "' + obj.value + '"')
  } else {
    return new Function('x', 'return x ' + obj.operator + ' ' + obj.value)
  }
}

const transformCustom = (str, obj) => {
  const s = str.replace(/\$\{(.*?)\}/g, (_, key) => {
    if (Object.prototype.hasOwnProperty.call(obj, key)) {
      return obj[key].value
    } else {
      throw new Error('自定义条件执行异常找不到变量')
    }
  })
  const f = new Function('x', 'return ' + s)
  console.log(f())
  return f()
}

const props = defineProps(['disabled'])
const formData = defineModel('formData')
const emit = defineEmits(['reset'])
</script>

<style lang="less" scope>
.ant-form-item {
  &.itemTitle {
    margin: 24px 0 12px;

    .title {
      height: 32px;
      padding-left: 16px;
      font-size: 14px;
      font-weight: 600;
      line-height: 32px;
    }
  }

  &.itemTitle:first-child {
    margin-top: 0;
  }

  &.itemTitle &.subitemName {
    margin-bottom: 0;
  }

  &.subitemNameCheckbox {
    margin-bottom: 0;
  }

  .ant-select:not(.ant-select-customize-input) .ant-select-selector {
    border: 1px solid #dcdfe6;
  }
}

html[theme='light'] {
  .ant-form-item {
    font-size: 14px;

    &.itemTitle {
      background: #f7f8fa;

      .title {
        color: #1d2129;
      }
    }
  }
}

.red {
  color: #ff1313;
}

.living-form .ant-select.ant-select-in-form-item {
  width: 100%;
}
</style>
